package com.cya.forumproject.controller;

import com.cya.forumproject.common.AppResult;
import com.cya.forumproject.common.ResultCode;
import com.cya.forumproject.config.AppConfig;
import com.cya.forumproject.model.Message;
import com.cya.forumproject.model.User;
import com.cya.forumproject.services.IMessageService;
import com.cya.forumproject.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/9/27 16:10
 * @description：
 * @modified By：
 * @version:
 */
@RestController
@RequestMapping("/messgae")
@Slf4j
@Api(tags = "站内信接口")
public class MessageController {


    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

@ApiOperation("发送站内信")
@PostMapping("/send")
    public AppResult send(@ApiParam("接受者id")@RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("内容")@RequestParam("content") @NonNull String content,
                          HttpServletRequest request){
    HttpSession session=request.getSession(false);
    User user= (User) session.getAttribute(AppConfig.USER_SESSION);



//1.当前登录用户的状态，如果被禁言不能发私信
    if (user.getState()==1){
        return AppResult.failed(ResultCode.FAILED_USER_BANNED);
    }
// 2.   不能给自己发私信
    if (user.getId()==receiveUserId){
        return AppResult.failed("不能给自己私信");
    }

//  3. 校验接收者是否存在
    User user1 = userService.selectById(receiveUserId);
    if (user1==null||user1.getDeleteState()==1){
        return AppResult.failed("接收者状态异常");
    }


//    4.封装对象
    Message message=new Message();
    message.setPostUserId(user.getId());
    message.setContent(content);
    message.setReceiveUserId(receiveUserId);
    message.setCreateTime(new Date());
    message.setUpdateTime(new Date());
    
//    5.调用service
    messageService.create(message);
//    6.返回结果
        return AppResult.success("发送成功");
    }

    @ApiOperation("查看未读帖子数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
    HttpSession session=request.getSession(false);
    User user = (User) session.getAttribute(AppConfig.USER_SESSION);
    if (user==null||user.getDeleteState()==1){
        return AppResult.failed("接收者状态异常");
    }
        Integer integer = messageService.selectUnreadCount(user.getId());//当前登录者的id是接受者的id

        return AppResult.success(integer);
    }

    @ApiOperation("获取登陆用的所有私信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){

    HttpSession session=request.getSession(false);
    User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        List<Message> messages = messageService.selectByReceiveUserId(user.getId());

        return AppResult.success(messages);
    }

    @ApiOperation("更新私信状态")
    @PostMapping("/markRead")
    public AppResult markRead(@ApiParam("站内信id")@RequestParam("id")@NonNull Long id ,HttpServletRequest request){
//根据id查询站内信
        Message message = messageService.selectById(id);
//        站内信是否存在
        if (message==null||message.getDeleteState()==1){
            return AppResult.failed("站内信不存在");
        }
        HttpSession session=request.getSession(false);
//        判断站内信是否是自己的
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getId()!=message.getReceiveUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        messageService.updateStateById(id, (byte) 1);


        return AppResult.success();
    }


    @ApiOperation("回复私信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,@ApiParam("要回复站内信id")@RequestParam("repliedId")@NonNull Long repliedId,
                           @ApiParam("要回复站内信内容")@RequestParam("content")@NonNull  String content)
    {
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        Message existMessage = messageService.selectById(repliedId);
        if (existMessage==null||existMessage.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED);
        }
        if (user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if (user.getId()==existMessage.getPostUserId()){
            return AppResult.failed("你不能给自己回复");
        }
        Message message= new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existMessage.getPostUserId());
        message.setContent(content);
        messageService.reply(repliedId,message);
        return AppResult.success();
    }
}